package com.daisuxia.web.listener;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.daisuxia.back.service.ITaskJob;
import com.daisuxia.constant.Constant;
import com.daisuxia.risk.utils.ConstantRisk;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;

/**
 * 首页init
 * 
 * @author gaoyuhai 2016-12-10 下午05:23:32
 */
public class IndexInit implements ServletContextListener {

	private static Logger loger = Logger.getLogger(IndexInit.class);
	private List<Object> starters = new ArrayList<Object>();

	public IndexInit() {
		addStarter(new SystemConfigStarter());

	}

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
	}

	public TreeSet<String> getKeys(String pattern, JedisCluster jedisCluster) {
		TreeSet<String> keys = new TreeSet<String>();
		Map<String, JedisPool> clusterNodes = jedisCluster.getClusterNodes();
		for (String k : clusterNodes.keySet()) {
			JedisPool jp = clusterNodes.get(k);
			Jedis connection = jp.getResource();
			try {
				keys.addAll(connection.keys(pattern));
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				connection.close();// 用完一定要close这个链接！！！
			}
		}
		return keys;
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(arg0.getServletContext());
		JedisCluster jedisCluster = (JedisCluster) ctx.getBean("jedisCluster");
		// initIndex(indexService, jedisCluster);
		jedisCluster.del(Constant.ALLOW_IP);
		Iterator<Object> it = starters.iterator();
		while (it.hasNext()) {
			Starter s = (Starter) it.next();
			s.init(arg0.getServletContext());
		}
		jedisCluster.del(ConstantRisk.RISK_ANALYSIS);
		jedisCluster.del(ConstantRisk.JXL_WAIT_ANALYSIS);
		jedisCluster.del(ConstantRisk.CAL_MONEY);
		jedisCluster.del("channel_report");
		TreeSet<String> keys = getKeys(ConstantRisk.REVIEW_BORROW + "*", jedisCluster);
		if (keys != null && keys.size() > 0) {
			for (String key : keys) {
				jedisCluster.del(key);
			}
		}
		keys = getKeys(ConstantRisk.JXL_REPORT + "*", jedisCluster);
		if (keys != null && keys.size() > 0) {
			for (String key : keys) {
				jedisCluster.del(key);
			}
		}
		keys = getKeys(ConstantRisk.USER_MONEY + "*", jedisCluster);
		if (keys != null && keys.size() > 0) {
			for (String key : keys) {
				jedisCluster.del(key);
			}
		}

		ITaskJob taskJob = (ITaskJob) ctx.getBean("taskJob");
		//loanMoneyAbout(taskJob);

	}

	void addStarter(Starter startup) {
		starters.add(startup);
	}

	/**
	 * 更新所有缓存
	 */
	public void updateCache() {
		ServletContext ctx = ContextLoader.getCurrentWebApplicationContext().getServletContext();
		Iterator<Object> it = starters.iterator();
		while (it.hasNext()) {
			Starter s = (Starter) it.next();
			s.init(ctx);
		}
	}

	public void updateRiskCache() {
		ServletContext ctx = ContextLoader.getCurrentWebApplicationContext().getServletContext();
		Iterator<Object> it = starters.iterator();
		while (it.hasNext()) {
			Starter s = (Starter) it.next();
			s.risk(ctx);
		}
	}

	/**
	 * 放款相关操作 用户放款、拒就送活动、查询打款信息
	 * 
	 */
	//TODO-ZSH
	public void loanMoneyAbout(ITaskJob taskJobf) {

		//final ITaskJob taskJob = taskJobf;
		// 定时放款用户===========================================================
/*		Thread tloanUser = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					while (true) {
						// TestC.systemoutCurrentTime(" cmb  loan_user begin  Thread 开始打款线程");
						taskJob.updateLoanTerm();
						// ssTestC.systemoutCurrentTime(" cmb  loan_user end    Thread 结束打款线程 ");
						try {
							Date nowDate = new Date();
							int nowHour = nowDate.getHours();
							int monutes = nowDate.getMinutes();
							// 避免交替日打款错误，23点55到第二天0点05分期间，不打款
							if (nowHour == 23 && monutes > 55) {
								Thread.sleep(1000 * 60 * 10);
							} else {
								Thread.sleep(1000 * 30);// 睡眠30秒
							}
						} catch (InterruptedException e) {
						}
					}
				} catch (Exception e) {
					loger.error("cmb  loan_user   error  用户放款  错误！", e);
				}

			}
		});*/

		// 定时查询打款状态===========================================================
/*
		Thread tQueryLoanState = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					while (true) {
						taskJob.queryPaysStateNotCmb();
						taskJob.queryPaysStateCmb();
						try {
							Thread.sleep(1000 * 60 * 2);// 2分钟执行一次
						} catch (InterruptedException e) {
						}

					}
				} catch (Exception e) {
					loger.error("query user state   error  查询打款状态错误！", e);
				}

			}
		});*/

		// 定时放款服务费===========================================================

/*		Thread tloanFee = new Thread(new Runnable() {
			@Override
			public void run() {

				try {
					while (true) {
						Date nowDate = new Date();
						int nowHour = nowDate.getHours();
						loger.error("begin payLoanInterestPays:" + nowDate);
						taskJob.payLoanInterestPays(null);
						// }
						try {
							Thread.sleep(1000 * 60 * 30);// 睡眠半个小时
						} catch (InterruptedException e) {
						}
					}

				} catch (Exception e) {
					loger.error("payLoanInterestPays   error  服务费打款  错误！", e);

				}
			}
		});*/

		// 据就送活动
	/*	if (PropertiesUtil.get("CMB_ISRUN").equals("YES")) {

			// 招行用户打款
			tloanUser.start();

			// 招行服务费打款
			tloanFee.start();

			// 查询打款状态
			tQueryLoanState.start();

			try {

				ThreadPool3.getInstance().run(new Runnable() {
					@Override
					public void run() {

						loger.error("ljujiusong  begin  begin  fuwufeu Thread");
						while (true) {
							taskJob.updateThreeLoanTerm();
							try {
								Thread.sleep(1000 * 60);
							} catch (InterruptedException e) {
								loger.error("updateThreeLoanTerm sleep", e);
							}// 睡眠30秒
						}
					}
				});
			} catch (Exception e) {
				loger.error("ljujiusong  thread error", e);
			}
		}*/

	}
}
